package org.nowcoder.leetcode.DP;

/**
 * Title  : 213. House Robber II
 * Source : https://leetcode.cn/problems/house-robber-ii/description/
 * Author : XrazYang
 * Date   : 2023-12-21
 */

public class LeetCode_213 {
    private int robRange(int[] nums, int start, int end) {
        //1. 定义状态：dp[i] : 到第i户最大盗取金额
        int[] dp = new int[nums.length];

        //2. 初始状态
        dp[start] = nums[start];

        //3. 状态转移方程
        for (int i = start + 1; i <= end; i++) {
            if (i - 1 == start) {
                dp[i] = Math.max(dp[i - 1], nums[i]);
            } else {
                dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
            }
        }
        return dp[end];
    }


    public int rob(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        if (nums.length == 2) {
            return Math.max(nums[0], nums[1]);
        }
        return Math.max(robRange(nums, 0, nums.length - 2), robRange(nums, 1, nums.length - 1));
    }
}
